package com.cloudcentral.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.DetectStrategy;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.mapper.DetectStrategyMapper;
import com.cloudcentral.util.Utils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;

/**
 * <p>
 * 探测任务24小时策略表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-11-23
 */
@Slf4j
@Service
public class DetectStrategyService extends ServiceImpl<DetectStrategyMapper, DetectStrategy> {

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean modify(Map<String, Object> params) throws Exception {
    DetectStrategy detectStrategy = new DetectStrategy();
    Field[] fields = DetectStrategy.class.getDeclaredFields();
    fields = Arrays.stream(fields).filter(item -> !item.getName().equalsIgnoreCase("params")).toArray(Field[]::new);
    for (Field field : fields) {
      String key = field.getName();
      Object value = params.get(key);
      if (value != null) Utils.reflectFieldValue(detectStrategy, field, value);
      params.remove(key);
    }
    detectStrategy.setParams(JSON.toJSONString(params));
    if (detectStrategy.getId() == null) throw new FailureException("缺少ID");
    else if (detectStrategy.getDetectId() == null) throw new FailureException("缺少任务ID");
    else if (detectStrategy.getHour() == null) throw new FailureException("缺少时段");
    else if (StringUtils.isBlank(detectStrategy.getParams())) throw new FailureException("缺少额外参数");
    else return updateById(detectStrategy);
  }
}
